/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.quarkus.example.datasource;

import static org.assertj.core.api.Assertions.assertThat;

import jakarta.inject.Inject;
import java.util.List;

import io.quarkus.test.junit.QuarkusTest;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.history.HistoricVariableInstance;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

@QuarkusTest
public class ApprovalProcessTest {

  @Inject
  protected ApprovalServiceBean approvalBean;

  @Inject
  protected HistoryService historyService;

  @AfterEach
  protected void cleanUp() {
    // remove historic variables between tests
    List<HistoricVariableInstance> variables = historyService
        .createHistoricVariableInstanceQuery().list();

    for (HistoricVariableInstance hvi : variables) {
      historyService.deleteHistoricVariableInstance(hvi.getId());
    }
  }

  @Test
  public void shouldApproveSuccessfullyOnPositiveAmount() {
    // given
    int positiveAmount = 100;

    // when
    approvalBean.evaluateForApproval(positiveAmount);

    // then
    // the whole transaction was successful
    // and historic variables are persisted
    List<HistoricVariableInstance> variables = historyService
        .createHistoricVariableInstanceQuery()
        .list();
    assertThat(variables).hasSize(2);
  }

  @Test
  public void shouldFailAndRollbackOnNegativeAmount() {
    // given
    int negativeAmount = -100;

    // when
    try {
      approvalBean.evaluateForApproval(negativeAmount);
    } catch (IllegalArgumentException ex) {
      // noop
    }

    // then
    // the whole transaction failed, was rolled back
    // and no historic variables are persisted
    List<HistoricVariableInstance> variables = historyService
        .createHistoricVariableInstanceQuery()
        .list();
    assertThat(variables).hasSize(0);
  }
}